// 01-deploy-fund-me.js
const { network, run } = require('hardhat')
const {
	developmentChains,
	networkConfig,
	LOCK_TIME,
	BLOCK_CONFIRMATIONS,
} = require('../helper-hardhat-config')

module.exports = async ({ getNamedAccounts, deployments }) => {
	const { deploy } = deployments
	const { firstAccount } = await getNamedAccounts()

	let dataFeedAttr
	let blockConfirmations
	if (developmentChains.includes(network.name)) {
		MockV3Aggregator = await deployments.get('MockV3Aggregator')
		dataFeedAttr = MockV3Aggregator.address
		blockConfirmations = 0
	} else {
		// 根据网络配置文件中的链ID获取价格数据源地址
		dataFeedAttr = networkConfig[network.config.chainId].ethUsdPriceFeed
		blockConfirmations = BLOCK_CONFIRMATIONS
	}

	console.log('----------------------------------------------------')
	console.log(`Network: ${network.name}`)
	console.log(`Deploying with account: ${firstAccount}`)
	console.log('Deploying FundMe...')

	const fundMe = await deploy('FundMe', {
		from: firstAccount, // 合约部署人
		args: [LOCK_TIME, dataFeedAttr], // 合约构造函数参数
		log: true, // 是否打印日志
		waitConfirmations: blockConfirmations, // 等待区块确认数
	})
	console.log('Waiting for block confirmations...')
	console.log(`FundMe deployed at: ${fundMe.address}`)
	console.log('----------------------------------------------------')

	// 验证sepolia合约
	// 一直报连接超时错误,暂未解决
	// if (network.config.chainId == 11155111 && process.env.ETHERSCAN_API_KEY) {
	// 	try {
	// 		console.log('Verifying contract...')
	// 		await run('verify:verify', {
	// 			address: fundMe.address,
	// 			constructorArguments: [LOCK_TIME, dataFeedAttr],
	// 		})
	// 		console.log('Contract verified!')
	// 	} catch (error) {
	// 		if (error.message.toLowerCase().includes('already verified')) {
	// 			console.log('Contract already verified!')
	// 		} else {
	// 			console.log('Verification failed:', error)
	// 		}
	// 	}
	// } else {
	// 	console.log('Network is not sepolia, verification skipped!')
	// }
}

module.exports.tags = ['all', 'fundme']
